import axios from 'axios';

// 创建 Axios 实例
const http = axios.create({
    baseURL: 'http://localhost:8080', // 替换为您的后端 API 地址
    timeout: 10000, // 请求超时时间
});

// 请求拦截器
http.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
http.interceptors.response.use(
    (response) => {
        // 对响应数据做一些处理
        return response.data;
    },
    (error) => {
        // 对响应错误做一些处理
        if (error.response && error.response.status === 401) {
            // 如果未授权，跳转到登录页面
            localStorage.removeItem('token'); // 清除 token
            localStorage.removeItem('userRole'); // 清除用户角色
            window.location.href = '/';
        }
        return Promise.reject(error);
    }
);

// 获取大棚信息
export const getGreenhouseInfo = async (id) => {
    try {
        const response = await http.get(`/api/greenhouse/${id}`);
        return response;
    } catch (error) {
        console.error('Failed to fetch greenhouse info:', error);
        throw error;
    }
};

// 获取传感器数据
export const getSensorData = async () => {
    try {
        const response = await http.get('/api/sensor-data');
        return response;
    } catch (error) {
        console.error('Failed to fetch sensor data:', error);
        throw error;
    }
};

// 获取土壤氮含量数据
export const getSoilNitrogenData = async () => {
    try {
        const response = await http.get('/api/soil-nitrogen');
        return response;
    } catch (error) {
        console.error('Failed to fetch soil nitrogen data:', error);
        throw error;
    }
};

// 获取摄像头图片URL
export const getCameraImageUrl = async (deviceSerial) => {
    try {
        const response = await http.get('/api/camera-image', {
            params: { deviceSerial }
        });
        return response;
    } catch (error) {
        console.error('Failed to fetch camera image URL:', error);
        throw error;
    }
};

export default http;